package com.hundun.util;


import com.hundun.util.bean.QinIuBean;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;


public final class ImageUtils {

    public static Font getFont(String fontName, int fontSize) {
        return getFont(fontName, null, fontSize);
    }


    /**
     * 获取文字字体
     *
     * @param fontName  字体名
     * @param fontStyle 字体样式
     * @param fontSize  字体大小
     * @return 字体
     */
    public static Font getFont(String fontName, Integer fontStyle, int fontSize) {
        Font defaultFont = new Font("宋体", Font.BOLD, fontSize);
        Font font;
        if (fontStyle != null) {
            //普通字体
            font = new Font(fontName, fontStyle, fontSize);
        } else {
            //艺术字
            font = FontUtils.getFont(fontName, fontSize);
            if (font == null) {
                //默认字体
                font = defaultFont;
            }
        }
        return font;
    }

    /**
     * 在图片上添加文字
     *  @param pressText    水印文字
     * @param srcImageFile 原图路径
     * @param desImageFile 目标图路径
     * @param fontColor    字体颜色
     * @param font         字体对象
     * @param x            横坐标
     * @param y            纵坐标
     * @param alpha        透明度
     * @return
     */
    public static String pressText(String pressText, String srcImageFile, String desImageFile,
                                   Color fontColor, Font font,
                                   int x, int y, float alpha) {
        try {
            File img = new File(srcImageFile);
            Image src = ImageIO.read(img);
            int width = src.getWidth(null);
            int height = src.getHeight(null);
            BufferedImage image = new BufferedImage(width, height,
                    BufferedImage.TYPE_INT_RGB);
            Graphics2D g = image.createGraphics();
            g.drawImage(src, 0, 0, width, height, null);
            g.setColor(fontColor);
            g.setFont(font);
            //设置透明度
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
            // 在指定坐标（图片居中）绘制水印文字
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);
            g.drawString(pressText, (width - (getLength(pressText) * font.getSize())) / 2 + x,
                    (height - font.getSize()) / 2 + y);
            g.dispose();
            // 输出到文件流
            ImageIO.write(image, "JPEG", new File(desImageFile));
            return desImageFile;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 绘画上传七牛云
     * @return
     */
    public static String getQinNiuUrl(String desImageFile) throws IOException {
        File file = new File(desImageFile);
        InputStream inputStream = new FileInputStream(file);
        MultipartFile multipartFile = new MockMultipartFile(file.getName(), inputStream);
        QinIuBean qinIuBean = new QiniuUtil().upload(multipartFile.getBytes(), System.currentTimeMillis() + "qianm");
        String url = QiniuUtil.QINNIU_URL + qinIuBean.key;
        return url;
    }


    /**
     * 绘制水印图片
     *
     * @param pressImgFile 水印图片
     * @param srcImageFile 原图
     * @param desImageFile 目标图
     * @param x            横坐标
     * @param y            纵坐标
     * @param alpha        透明度
     */
    public static void pressImage(String pressImgFile, String srcImageFile, String desImageFile,
                                  int x, int y, float alpha,int widths) {
        try {
            File img = new File(srcImageFile);
            Image src = ImageIO.read(img);
            int width = src.getWidth(null);
            int height = src.getHeight(null);
            BufferedImage image = new BufferedImage(width, height,
                    BufferedImage.TYPE_INT_RGB);
            Graphics2D g = image.createGraphics();
            //设置透明度
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
                    alpha));
            g.drawImage(src, 0, 0, 120, 120, null);
            // 水印图片
            BufferedImage imgIcon = ImageIO.read(new File(pressImgFile));
            int imgIconWidth = (int) (imgIcon.getWidth());
            int imgIconHeight = (int) (imgIcon.getHeight() );
            //设置透明度
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
                    1f));
            //居中绘制水印图片
            g.drawImage(imgIcon, (120 - imgIconWidth) / 2 + x,
                    (120 - imgIconHeight) / 2 + y, imgIconWidth/widths, imgIconHeight/widths, null);
            //释放画板
            g.dispose();
            ImageIO.write(image, "PNG", new File(desImageFile));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    /**
     * 得到文本长度的一半
     *
     * @param text 文本
     * @return 文本总长度的一半
     */
    public static int getLength(String text) {
        int length = 0;
        for (int i = 0; i < text.length(); i++) {
            if ((text.charAt(i) + "").getBytes().length > 1) {
                //中文2个字节
                length += 2;
            } else {
                //非中文1个字节
                length += 1;
            }
        }
        return length / 2;
    }


    /**
     * 图像类型转换
     *
     * @param srcImageFile 原图路径
     * @param formatName   目标图格式
     * @param desImageFile 目标图路径
     */
    public static void convert(String srcImageFile, String formatName, String desImageFile) {
        try {
            File imageFile = new File(srcImageFile);
            if (imageFile.canRead() && imageFile.canWrite()) {
                BufferedImage src = ImageIO.read(imageFile);
                ImageIO.write(src, formatName, new File(desImageFile));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    /**
     * graphics 把头像图片切成圆图
     *
     * @param url
     * @return
     */
    public static String getLogo(String url,String name,String word,String pressImgFile, String srcImageFile, String desImageFile, String backgroundFile,String endFile) throws IOException {
        BufferedImage avatarImage = ImageIO.read(new URL(url));
        int width = 100;
        // 透明底的图片
        BufferedImage formatAvatarImage = new BufferedImage(width, width, BufferedImage.TYPE_4BYTE_ABGR);
        Graphics2D graphics = formatAvatarImage.createGraphics();
        //把图片切成一个圓
        {
            graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            //留一个像素的空白区域，这个很重要，画圆的时候把这个覆盖
            int border = 1;
            //图片是一个圆型
            Ellipse2D.Double shape = new Ellipse2D.Double(border, border, width - border, width - border );
            //需要保留的区域
            graphics.setClip(shape);
            graphics.drawImage(avatarImage, border, border, width - border , width - border , null);
            graphics.dispose();
        }
        //在圆图外面再画一个圆
        {
            //新创建一个graphics，这样画的圆不会有锯齿
            graphics = formatAvatarImage.createGraphics();
            graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            int border = 3;
            //画笔是4.5个像素，BasicStroke的使用可以查看下面的参考文档
            //使画笔时基本会像外延伸一定像素，具体可以自己使用的时候测试
            Stroke s = new BasicStroke(4.5F, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
            graphics.setStroke(s);
            graphics.setColor(Color.WHITE);
            graphics.drawOval(border, border, width - border * 2, width - border * 2);
            graphics.dispose();
        }
        try (OutputStream os = new FileOutputStream(pressImgFile)) {
            ImageIO.write(formatAvatarImage, "PNG", os);
        }
        BufferedImage logo = ImageIO.read(new URL(url));
        Graphics2D g = logo.createGraphics();
        //设置透明度
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
                0.5f));
        g.drawImage(logo, 0, 0, logo.getWidth(), logo.getHeight(), null);
        g.dispose();
        // 输出到文件流
        ImageIO.write(logo, "PNG", new File(srcImageFile));

        //制作头像
        String end  =  ImageUtils.getHead(srcImageFile,pressImgFile,backgroundFile,name);
        //logo
//        ImageUtils.pressImage(pressImgFile, srcImageFile, desImageFile, 0, 0, 0.6f,1);


//        //背景
//        ImageUtils.pressImage(backgroundFile,desImageFile,endFile,60,60,1,2);
//
//        Font systemFont = getFont("幼圆", Font.BOLD, 15);
//        ImageUtils.pressText(name, endFile, "e:/img/12345.png",
//                Color.white, systemFont,
//                0,260, 1f);
////        String word = "我姓郑却挣不到你的心";
//        Font systemFonts = getFont("幼圆", Font.BOLD, 8);
//        ImageUtils.pressText(word, "e:/img/12345.png", "e:/img/end.png",
//                Color.white, systemFonts,
//                0,28, 1f);
        return end;
//        return desImageFile;
    }

    /**
     * 文字添加透明背景图
     */
    public static String getWord(String word,String url){
        try
        {
            int width = 400;
            int height =40;
            int fontHeight = 20;
            String words = "e:/img/word.jpg";
            BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D gd = buffImg.createGraphics();
            //设置透明  start
            buffImg = gd.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
            gd.setBackground(Color.WHITE);//设置背景色
            gd=buffImg.createGraphics();
            //设置透明  end
            gd.setFont(new Font("幼圆", Font.BOLD, fontHeight)); //设置字体
            gd.setColor(Color.orange); //设置颜色
//            gd.drawRect(0, 0, width - 1, height - 1); //画边框
            gd.drawString(word, width/2-fontHeight*word.length()/2,fontHeight); //输出文字（中文横向居中）
            File imgFile=new File(words);
            ImageIO.write(buffImg, "PNG", imgFile);
            return words;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     *
     * @param masterImg 原图
     * @param logoImg logo
     * @param background 背景
     * @param name 姓名
     * @return
     */
    public static String getHead(String masterImg,String logoImg,String background,String name) throws IOException {
        File img = new File(masterImg);
        Image master = ImageIO.read(img);
        int width = 120;
        int height = 120;
        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();
        //设置透明度
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
               0.7f));
        //原图
        g.drawImage(master, 0, 0, width, height, null);


        // LOGO图片
        BufferedImage imgLogo = ImageIO.read(new File(logoImg));
        int imgIconWidth = (int) (imgLogo.getWidth()/2);
        int imgIconHeight = (int) (imgLogo.getHeight()/2);
        //设置透明度
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
                1f));
        //居中绘制水印图片
        g.drawImage(imgLogo, (120 - imgIconWidth) / 2 + 0,
                (120 - imgIconHeight) / 2 - 20, imgIconWidth, imgIconHeight, null);

        // 背景图片
        BufferedImage imgBackground = ImageIO.read(new File(background));
        int imgBackgroundWidth = (int) (imgBackground.getWidth()/2);
        int imgBackgroundHeight = (int) (imgBackground.getHeight()/1.2);
        //设置透明度
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
                0.7f));
        //居中绘制水印图片
        g.drawImage(imgBackground, (120 - imgBackgroundWidth) / 2 + 0,
                (120 - imgBackgroundWidth) / 2 + 60, imgBackgroundWidth, imgBackgroundHeight, null);
        //文字

        String word = "廖";
        Font systemFonts = getFont("幼圆", Font.BOLD, 15);
        g.setColor(Color.white);
        g.setFont(systemFonts);
        //设置透明度
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 1f));
        // 在指定坐标（图片居中）绘制水印文字
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        g.drawString(word, (width - (getLength(word) * 20)) / 2 +0,
                (height - 20) / 2 + 35);

        String words = "你是猪头三吗?";
        Font systemFont = getFont("幼圆", Font.BOLD, 10);
        g.setColor(Color.white);
        g.setFont(systemFont);
        //设置透明度
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 1f));
        // 在指定坐标（图片居中）绘制水印文字
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        g.drawString(words, (width - (getLength(word) * 20)) / 2 +0,
                (height - 20) / 2 + 40);




        g.dispose();
        String end = "E:/img/newLogo.PNG";
        ImageIO.write(image, "PNG", new File(end));
        return end;
    }


}
